var ybname = '天然气';
var millName; //染厂名称
var millData = [];
var openID;
var hgS2;
var Judge_cp;
var Judge_bp;

var code = getQueryString("code");

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//初始化
$(function () {

    /*设置日期默认值*/
    var etime = new Date();
    $('#appDateTime').val(formatterSDate(etime));
    $('#appDateTime02').val(formatterEDate(etime));


    console.log('code=' + code);
    getopenid();

    createA();
    createB();

});


function getopenid() {
    console.log(
        'https://www.xdfznh.club/wxpadbe/switch/oao/'
        + code);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/switch/oao/'
            + code,
        type: 'get',
        dataType: 'json',
        // 成功回调
        success: function (data) {
            console.log('请求成功');
            openID = data.data;
            console.log('openID=' + openID);
            getmill();
        },
        //失败回调
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    })
}

//获取微信号对应的染厂名称
function getmill() {
    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/userMillController/selectMills/'
            + openID,

        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data.length);
            var ID;
            var liNodes = document.getElementsByTagName("input");
            if (data.length == 0) {
                // 关闭当前页面
                alert('当前用户没有权限！');

            }

            if (data.length > 0) {
                millName = data[0].mill;

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                getJurisdiction(); //获取个人查看报表的权限
                getDropDownDate(); // 设置下拉

            };
        }
    })
};

//获取个人查看报表的权限
function getJurisdiction() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                millName = data[0].mill;
                var cp = eval('(' + data[0].rpt_cp + ')');
                var bp = eval('(' + data[0].rpt_bp + ')');

                if (cp) {
                    Judge_cp = true;
                    getData();
                    getsum()
                } else {
                    Judge_cp = false;
                    alert('当前用户没有查看成品权限！');
                }
                if (bp) {
                    Judge_bp = true;
                    getData1();
                    getsum()
                } else  {
                    Judge_bp = false;
                    alert('当前用户没有查看白坯权限！');
                }

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                // console.log(millData);
                getDropDownDate(); // 设置下拉

            } else {
                Judge_cp = false;
                Judge_bp = false;
                alert('当前用户没有查看报表权限！');
            }
            ;
        }
    })

}



function getData() {
    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call PurchaseAndSale('"
        + document.getElementById("appDateTime").value
        +"','"
        + document.getElementById("appDateTime02").value
        + "','成品')");

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call PurchaseAndSale('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "','成品')",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            $('#waterdetai').datagrid('loadData', data);

        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }

    })

}

function getData1() {
    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call PurchaseAndSale('"
        + document.getElementById("appDateTime").value
        +"','"
        + document.getElementById("appDateTime02").value
        + "','白坯')");

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call PurchaseAndSale('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "','白坯')",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            $('#waterdetai01').datagrid('loadData', data);

        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }

    })
}

/******************************************************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

formatterSDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + "07" + ":" + "00"*/;
};

formatterEDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    var hor = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var min = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    ;
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + hor + ":" + "00"*/;
};


/*****************************************************************************************/

/*自定义本月日期时间*/
customSDateMonth = function (date) {
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + "01";
};

//计算当前日期的前后几天的日期
function getDay(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate;
}

function doHandleMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
}

/*查询一天的日期设置*/
function getdaydate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-1));
    $('#appDateTime02').val(getDay(-1));

    getquery();
}

/*查询一周的日期设置*/
function getWeekdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询一个月的日期设置*/
function getOneMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-30));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询本月的日期设置*/
function getMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(customSDateMonth(etime));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}


/********************************************************************************/
/*获取标签的序号*/
function getTabSelectedIndex() {
    return $('#tabs').tabs('getTabIndex', $('#tabs').tabs('getSelected'));
}

//获取标签下网格被选中的行的数据
function getClientName() {
    var clientName;
    var Sdate= document.getElementById("appDateTime").value;
    var Edate= document.getElementById("appDateTime02").value;
    switch (getTabSelectedIndex()) {
        case 0:
            var selected1 = $('#waterdetai').datagrid('getSelected');
            if (selected1 != undefined ) {

                clientName = selected1.clientname; //获取当前选中行客户名称
                getDataA(clientName,Sdate,Edate);
                getsumA();
                $('#A').window('open');
                $('#A').panel({title: "成品明细 - "+ clientName});
                break;

            }else{
                //   未选择
                $.messager.alert('确认', '未选择客户，无法查询明细！');
                return;
            }

        case 1:

            var selected2 = $('#waterdetai01').datagrid('getSelected');
            if (selected2 != undefined ) {
                clientName = selected2.clientname; //获取当前选中行客户名称
                getDataB(clientName,Sdate,Edate);
                getsunB();

                $('#B').window('open');
                $('#B').panel({title: "白坯明细 - "+ clientName});
                break;

            }else{
                //   未选择
                $.messager.alert('确认', '未选择客户，无法查询明细！');
                return;
            }
    }
}



//查询事件
function getquery() {
    if (Judge_cp == true) {
        getData();
    }
    if (Judge_bp == true) {
        getData1();
    }
}


function imagetable() {
    location.href = 'html/BPCPAccess_image.html?millname=' + millName;
}

function getDropDownDate() {
    console.log('2=' + millData);
    hgS2 = new selectSwiper({
        el: '.select_box2',
        mustSelect: true,
        activeIndex: 0,
        data: millData,
        init: function (index) {
            if (index !== -1) {
                $('.btn2').html(this.data[index]);
            }
        },
        okFunUndefind: function () {
            alert('必须选择一项');
        },
        okFun: function (index) {
            $('.btn2').html(this.data[index]);
            millName = $('button').text();
            getJurisdictionmill();

        },
        closeFun: function () {
            console.log('取消');
        },
    });

    $('.btn2').on('click', function () {
        hgS2.openSelectSwiper();

    });
}

//在更换染厂之后  重新刷新数据  并判断个人权限
function getJurisdictionmill() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                var cp = eval('(' + data[0].rpt_cp + ')');
                var bp = eval('(' + data[0].rpt_bp + ')');

                if (cp) {
                    Judge_cp = true;
                    getData();
                    getsum()
                } else {
                    Judge_cp = false;
                    alert('当前用户没有查看成品权限！');
                }
                if (bp) {
                    Judge_bp = true;
                    getData1();
                    getsum()
                } else {
                    Judge_bp = false;
                    alert('当前用户没有查看白坯权限!');
                }

            } else {
                Judge_cp = false;
                Judge_bp = false;
                alert('当前用户没有查看报表权限！');
            }
            ;
        }
    })

}


function  getsum() {
    //成品
    $('#waterdetai').datagrid({
        showFooter: true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var rkqty = 0,fhqty = 0,kcqty = 0;
            var rkps = 0,fhps = 0, kcps = 0;
            var rkms = 0,fhms = 0, kcms = 0;

            for (let i = 0; i < data.length; i++) {
                rkqty += data[i].cprkqty ? parseFloat(data[i].cprkqty) : 0;
                fhqty += data[i].cpfhqty ? parseFloat(data[i].cpfhqty) : 0;
                kcqty += data[i].cpkcqty ? parseFloat(data[i].cpkcqty) : 0;

                rkps += data[i].cprkps ? parseFloat(data[i].cprkps) : 0;
                fhps += data[i].cpfhps ? parseFloat(data[i].cpfhps) : 0;
                kcps += data[i].cpkcps ? parseFloat(data[i].cpkcps) : 0;

                rkms += data[i].cprkmeter ? parseFloat(data[i].cprkmeter) : 0;
                fhms += data[i].cpfhmeter ? parseFloat(data[i].cpfhmeter) : 0;
                kcms += data[i].cpkcmeter ? parseFloat(data[i].cpkcmeter) : 0;
            }
            $(this).datagrid('reloadFooter', [{
              client_name: '合计',
                cprkqty: rkqty.toFixed(0), cpfhqty: fhqty.toFixed(0), cpkcqty: kcqty.toFixed(0),
                cprkps: rkps.toFixed(0), cpfhps: fhps.toFixed(0), cpkcps: kcps.toFixed(0),
                cprkmeter: rkms.toFixed(0), cpfhmeter: fhms.toFixed(0), cpkcmeter: kcms.toFixed(0),
            }])
        }
    });

    //白坯
    $('#waterdetai01').datagrid({
        showFooter: true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var rkqty = 0,llqty = 0,kcqty = 0;
            var rkps = 0,llps = 0, kcps = 0;
            var rkms = 0,llms = 0, kcms = 0;

            for (let i = 0; i < data.length; i++) {
                rkqty += data[i].bprkqty ? parseFloat(data[i].bprkqty) : 0;
                llqty += data[i].bpllqty ? parseFloat(data[i].bpllqty) : 0;
                kcqty += data[i].bpkcqty ? parseFloat(data[i].bpkcqty) : 0;

                rkps += data[i].bprkps ? parseFloat(data[i].bprkps) : 0;
                llps += data[i].bpllps ? parseFloat(data[i].bpllps) : 0;
                kcps += data[i].bpkcps ? parseFloat(data[i].bpkcps) : 0;

                rkms += data[i].bprkmeter ? parseFloat(data[i].bprkmeter) : 0;
                llms += data[i].bpllmeter ? parseFloat(data[i].bpllmeter) : 0;
                kcms += data[i].bpkcmeter ? parseFloat(data[i].bpkcmeter) : 0;
            }
            $(this).datagrid('reloadFooter', [{
                client_name: '合计',
                bprkqty: rkqty.toFixed(0), bpllqty: llqty.toFixed(0), bpkcqty: kcqty.toFixed(0),
                bprkps: rkps.toFixed(0), bpllps: llqty.toFixed(0), bpkcps: kcps.toFixed(0),
                bprkmeter: rkms.toFixed(0), bpllmeter: llqty.toFixed(0), bpkcmeter: kcms.toFixed(0),
            }])
        }
    });
}

//创建成品白坯模态窗
function createA(){

    $('#A').window({
        width: 600,
        height: 400,
        modal: true,
        title: '明细、进度',
        collapsible: false,//定义是否显示可折叠按钮
        minimizable: false,
        maximizable: false,
        closable: true,
        maximized: true,  //最大化
        closed: true      //初始化页面关闭不显示
    });
}
function createB(){

    $('#B').window({
        width: 600,
        height: 400,
        modal: true,
        title: '明细、进度',
        collapsible: false,//定义是否显示可折叠按钮
        minimizable: false,
        maximizable: false,
        closable: true,
        maximized: true,  //最大化
        closed: true      //初始化页面关闭不显示
    });
}


function getDataA(clientName,Sdate,Edate) {

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName
            + "/call PurchaseAndSaleDetail('"
            + Sdate
            + "','"
            + Edate
            + "','"
            + clientName
            + "'"
            + ",'成品')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            var data1;
            var data2;
            var data3;

            data1=data.filter(item=>item.b_detailtype==='成品入库');
            data2=data.filter(item=>item.b_detailtype==='成品出库');
            data3=data.filter(item=>item.b_detailtype==='成品库存');

            $('#waterdetaiA1').datagrid('loadData', data1);
            $('#waterdetaiA2').datagrid('loadData', data2);
            $('#waterdetaiA3').datagrid('loadData', data3);

            showColorA();
        }
    })
}

function showColorA() {
    $('#waterdetaiA2').datagrid({
        rowStyler: function (index, row) {
            if (row.b_order > 0) {
                return 'color:#FF0000 ';   //#E0ECFF
            }
        }
    });
}

function getsumA(){
    //成品入库
    $('#waterdetaiA1').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })

    //成品出库
    $('#waterdetaiA2').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })

    //成品库存
    $('#waterdetaiA3').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_pinming: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })
}


function getDataB(clientName,Sdate,Edate) {
    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName
            + "/call PurchaseAndSaleDetail('"
            + Sdate
            + "','"
            + Edate
            + "','"
            + clientName
            + "'"
            + ",'白坯')",
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var data1;
            var data2;
            var data3;

            console.log(11111)

            data1=data.filter(item=>item.b_detailtype==='白坯入库');
            data2=data.filter(item=>item.b_detailtype==='白坯领料');
            data3=data.filter(item=>item.b_detailtype==='白坯库存');


            $('#waterdetaiB1').datagrid('loadData', data1);
            $('#waterdetaiB2').datagrid('loadData', data2);
            $('#waterdetaiB3').datagrid('loadData', data3);

            showColorB();
        }
    })
}

//根据条件改变背景 色
function showColorB() {
    $('#waterdetaiB1').datagrid({
        rowStyler: function (index, row) {
            if (row.b_order > 0) {
                return 'color:#FF0000 ';   //#E0ECFF
            }
        }
    });
}

function getsunB() {
    //成品入库
    $('#waterdetaiB1').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })

    //成品出库
    $('#waterdetaiB2').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })

    //成品库存
    $('#waterdetaiB3').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps = 0;
            var ms = 0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                ms += data[i].b_meter ? parseFloat(data[i].b_meter) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_pinming: '合计',
                b_qty: qty.toFixed(1),
                b_ps: ps.toFixed(0),
                b_meter: ms.toFixed(0),
            }])
        }
    })

}




